import { createApp } from 'vue'
import vuetify from './vuetify'

// 创建Toast组件
const ToastComponent = {
  template: `
    <v-snackbar
      v-model="show"
      :color="color"
      :timeout="timeout"
      location="top"
    >
      {{ message }}
      <template v-slot:actions>
        <v-btn
          color="white"
          variant="text"
          @click="show = false"
        >
          关闭
        </v-btn>
      </template>
    </v-snackbar>
  `,
  data() {
    return {
      show: false,
      message: '',
      color: 'success',
      timeout: 3000
    }
  },
  methods: {
    success(message, timeout = 3000) {
      this.message = message
      this.color = 'success'
      this.timeout = timeout
      this.show = true
    },
    error(message, timeout = 3000) {
      this.message = message
      this.color = 'error'
      this.timeout = timeout
      this.show = true
    },
    warning(message, timeout = 3000) {
      this.message = message
      this.color = 'warning'
      this.timeout = timeout
      this.show = true
    },
    info(message, timeout = 3000) {
      this.message = message
      this.color = 'info'
      this.timeout = timeout
      this.show = true
    }
  }
}

// 创建Toast实例
let toastInstance = null

export function createToast() {
  if (!toastInstance) {
    const div = document.createElement('div')
    document.body.appendChild(div)
    
    const app = createApp(ToastComponent)
    app.use(vuetify)
    toastInstance = app.mount(div)
  }
  return toastInstance
}

// 全局Toast方法
export const toast = {
  success: (message, timeout) => {
    const instance = createToast()
    instance.success(message, timeout)
  },
  error: (message, timeout) => {
    const instance = createToast()
    instance.error(message, timeout)
  },
  warning: (message, timeout) => {
    const instance = createToast()
    instance.warning(message, timeout)
  },
  info: (message, timeout) => {
    const instance = createToast()
    instance.info(message, timeout)
  }
}
